require('dotenv').config()
// 导入数据库操作模块
const db = require('../../db')

// MARK 角色管理

// MARK GET / sys / role	分页查询角色列表
exports.getList = (req, res) => {
  const { page, pagesize } = req.query

  // 验证输入数据
  if (!page || !pagesize) {
    return res.status(400).json({ success: false, code: 10062, message: '分页参数不能为空' })
  }

  const pageNumber = parseInt(page, 10)
  const pageSize = parseInt(pagesize, 10)

  if (isNaN(pageNumber) || isNaN(pageSize) || pageNumber <= 0 || pageSize <= 0) {
    return res.status(400).json({ success: false, code: 10063, message: '分页参数必须是正整数' })
  }

  // 计算偏移量
  const offset = (pageNumber - 1) * pageSize

  // 查询角色列表
  const query = `
    SELECT 
        id,
        name,
        description,
        state
    FROM 
        role
    LIMIT ?, ?
  `

  db.query(query, [offset, pageSize], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10064, message: '查询角色列表失败', error: err.message })
    }

    // 查询总记录数
    const countQuery = `
      SELECT 
          COUNT(*) AS total
      FROM 
          role
    `

    db.query(countQuery, (err, countResult) => {
      if (err) {
        return res.status(500).json({ success: false, code: 10065, message: '查询总记录数失败', error: err.message })
      }

      const total = countResult[0].total

      // 格式化响应数据
      const data = {
        total: total,
        rows: results.map(row => ({
          id: row.id,
          name: row.name,
          description: row.description,
          state: row.state
        }))
      }

      res.json({
        success: true,
        code: 0,
        data: data,
        message: '查询角色列表成功'
      })
    })
  })
}
// MARK POST / sys / role	新增角色
exports.addNew = (req, res) => {
  const { name, description, state } = req.body

  // 验证输入数据
  if (!name || !description || state === undefined) {
    return res.status(400).json({ success: false, code: 10026, message: '必要字段不能为空' })
  }

  // 插入角色信息
  const insertQuery = `
    INSERT INTO role (name, description, state)
    VALUES (?, ?, ?)
  `

  db.query(insertQuery, [name, description, state], (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10027, message: '新增角色失败', error: err.message })
    }

    const newId = result.insertId

    res.json({
      success: true,
      code: 10000,
      data: { id: newId.toString() },
      message: '新增角色成功'
    })
  })
}
// MARK GET / sys / role / list / enabled	获取已启用角色列表
exports.getEnabled = (req, res) => {
  // 查询已启用角色
  const query = `
    SELECT 
        id,
        name
    FROM 
        role
    WHERE 
        state = 1
  `

  db.query(query, (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10051, message: '查询已启用角色失败', error: err.message })
    }

    // 格式化响应数据
    const data = results.map(row => ({
      id: row.id,
      name: row.name
    }))

    res.json({
      success: true,
      code: 10000,
      data: data,
      message: '获取启用角色列表成功'
    })
  })
}
// MARK GET / sys / role / { id }	获取角色详情
exports.getById = (req, res) => {
  const { id } = req.params

  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10052, message: '角色ID不能为空' })
  }

  // 查询角色信息
  const query = `
    SELECT 
        id,
        name,
        description,
        state,
        permIds
    FROM 
        role
    WHERE 
        id = ?
  `

  db.query(query, [id], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10053, message: '查询角色信息失败', error: err.message })
    }

    if (results.length === 0) {
      return res.status(404).json({ success: false, code: 10054, message: '角色不存在' })
    }

    const role = results[0]

    // 将 permIds 字段从逗号分隔的字符串转换为数组
    const permIdsArray = role.permIds ? role.permIds.split('、').map(Number) : []

    // 格式化响应数据
    const data = {
      id: role.id,
      name: role.name,
      description: role.description,
      state: role.state,
      permIds: permIdsArray
    }

    res.json({
      success: true,
      code: 10000,
      data: data,
      message: '获取角色详情成功'
    })
  })
}
// MARK PUT / sys / role / { id }	修改角色
exports.putById = (req, res) => {
  const { id } = req.params
  const { name, description, state } = req.body
  // MARK 初始角色维护
  if (id >= 1 && id <= 5) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
  }
  // 验证输入数据
  if (!name || !description || state === undefined) {
    return res.status(400).json({ success: false, code: 10023, message: '必要字段不能为空' })
  }

  // 更新角色信息
  const updateQuery = `
    UPDATE role
    SET 
        name = ?,
        description = ?,
        state = ?
    WHERE 
        id = ?
  `

  db.query(updateQuery, [name, description, state, id], (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10024, message: '更新角色信息失败', error: err.message })
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, code: 10025, message: '角色不存在' })
    }

    res.json({
      success: true,
      code: 10000,
      data: { id: id.toString() },
      message: '更新角色信息成功'
    })
  })
}
// MARK DELETE / sys / role / { id }	删除角色
exports.delById = (req, res) => {
  const { id } = req.params
  // MARK 维护初始数据
  if (id >= 1 && id <= 6) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
  }
  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10028, message: '角色ID不能为空' })
  }

  // 删除角色信息
  const deleteQuery = `
    DELETE FROM role
    WHERE 
        id = ?
  `

  db.query(deleteQuery, [id], (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10029, message: '删除角色信息失败', error: err.message })
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, code: 10030, message: '角色不存在' })
    }

    res.json({
      success: true,
      code: 10000,
      data: { id: id.toString() },
      message: '删除角色信息成功'
    })
  })
}
// MARK PUT / sys / role / assignPerm	分配角色权限
exports.setPermission = (req, res) => {
  const { id, permIds } = req.body
  console.log("permIds >>> ", permIds)
  // 验证输入数据
  if (!id) {
    return res.status(400).json({ success: false, code: 10056, message: '角色ID不能为空' })
  }
  // MARK 维护初始数据
  if (id >= 1 && id <= 5) {
    return res.status(200).json({ success: false, code: 10023, message: '初始数据不可操作' })
  }
  if (!Array.isArray(permIds)) {
    return res.status(400).json({ success: false, code: 10057, message: '权限ID列表必须是数组' })
  }

  // 将权限ID数组转换为逗号分隔的字符串
  const permIdsString = permIds.join('、')

  // 更新角色的 permIds 字段
  const updateQuery = `
    UPDATE role
    SET 
        permIds = ?
    WHERE 
        id = ?
  `

  db.query(updateQuery, [permIdsString, id], (err, result) => {
    if (err) {
      return res.status(500).json({ success: false, code: 10058, message: '更新角色权限失败', error: err.message })
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, code: 10059, message: '角色不存在' })
    }

    res.json({
      success: true,
      code: 10000,
      data: { id: id.toString() },
      message: '分配角色权限成功'
    })
  })
}